import axios from "axios";
import { Message, Loading } from 'element-ui';
import router from "./router"

let loading;
function startLoading(){
    loading = Loading.service({
        lock: true,
        text: '数据加载中',
        background: 'rgba(0,0,0,0.7)'
    })
}

function endLoading(){
    loading.close();
}

// 请求拦截
axios.interceptors.request.use(config => {
    startLoading();
    if(localStorage.eleToken){
        // 设置统一的请求头
        config.headers.Authorization = localStorage.eleToken
    }
    return config
}, error => {
    return Promise.reject(error)
})

//响应拦截
axios.interceptors.response.use(response => {
    endLoading();
    return response
}, error => {
    // 错误提醒
    endLoading();
    Message.error(error.response.data)
    console.log(error.response)

    // 获取错误状态码
    const {status} = error.response
    console.log(status)
    if(status === 0){
        Message.error("token失效,请重新登录")
        localStorage.removeItem('eleToken')
        // console.log(error)
        router.push('/login')
    }
    return Promise.reject(error)
})

export default axios